# -*- coding: utf-8 -*-
# @Date   : 2019/12/10
# @File   : R15_EC_AssetDisposalDebtGuarantorCompensation_WHB_2D.py
# @Author : breeze


'''eof
name:资产处置、呆账、保证人代偿
code:R15_EC_AssetDisposalDebtGuarantorCompensation_WHB_2D
tableName:
columnName:
groups:弱规则>企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''
import json
import sys
import pandas as pd
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def fac1(data):
    factor = []
    flag = False
    # 信用提示信息 EBA[1,1]
    EBA = getTable(data, 'EBA', 1, 1)
    if EBA == [{}]:
        return u'缺失值'
    elif EBA == 0:
        return 0
    else:
        # 信用提示信息单元 EB01[1,1]
        EB01 = getTable(EBA[0], 'EB01', 1, 0)
        if EB01 == [{}]:
            return u'缺失值'
        elif EB01 == 0:
            return 0
        else:
            # 信贷交易提示信息段 EB01A[0,1]
            EB01A = getTable(EB01[0], 'EB01A', 1, 1)
            if EB01A == [{}]:
                return u'缺失值'
            elif EB01A == 0:
                return 0
            else:
                for i in EB01A:
                    # 被追偿的借贷交易余额
                    EB01AJ02 = i.get("EB01AJ02")
                    if isfloat(EB01AJ02):
                        flag = True
                        if float(EB01AJ02) > 0:
                            factor.append(1)

    return len(factor) if flag else u'缺失值'


def fac2(data, num):
    # 借贷交易汇总信息 EBB[1,1]
    EBB = getTable(data, 'EBB', 1, 0)
    if EBB == [{}]:
        return u'缺失值'
    elif EBB == 0:
        return 0
    else:
        # 信贷交易汇总信息单元 EB02[0,1]
        EB02 = getTable(EBB[0], 'EB02', 0, 1)
        if EB02 == [{}]:
            return u'缺失值'
        elif EB02 == 0:
            return 0
        else:
            # 未结清信贷交易汇总信息段 EB02A[1,1]
            EB02A = getTable(EB02[0], 'EB02A', 1, 1)
            if EB02A == [{}]:
                return u'缺失值'
            elif EB02A == 0:
                return 0
            else:
                EB02A = EB02A[0]
                if num == 2:
                    # 资产处置业务账户数
                    EB02AS01 = EB02A.get("EB02AS01")
                    # 资产处置业务余额
                    EB02AJ01 = EB02A.get("EB02AJ01")
                    if isfloat(EB02AS01) or isfloat(EB02AJ01):
                        if (isfloat(EB02AS01) and float(EB02AS01) > 0) or (isfloat(EB02AJ01) and float(EB02AJ01) > 0):
                            return 1
                        else:
                            return 0
                    else:
                        return u'缺失值'
                elif num == 3:
                    # 资产处置业务账户数
                    EB02AS02 = EB02A.get("EB02AS02")
                    # 资产处置业务余额
                    EB02AJ02 = EB02A.get("EB02AJ02")
                    if isfloat(EB02AS02) or isfloat(EB02AJ02):
                        if (isfloat(EB02AS02) and float(EB02AS02) > 0) or (isfloat(EB02AJ02) and float(EB02AJ02) > 0):
                            return 1
                        else:
                            return 0
                    else:
                        return u'缺失值'
                else:
                    return u'缺失值'


def fac4(data, num):
    factor = []
    flag = False
    typeList = ["D1", "D2", "R1", "R4", "C1"]
    typeList2 = ["41", "51"]
    typeList3 = ["D1", "D2", "R1", "R4"]
    # 借贷账户信息 EDA[1,1]
    EDA = getTable(data, 'EDA', 1, 0)
    if EDA == [{}]:
        return u'缺失值'
    elif EDA == 0:
        return 0
    else:
        # 借贷账户信息单元 ED01[0,*]
        ED01 = getTable(EDA[0], 'ED01', 0, 1)
        if ED01 == [{}]:
            return u'缺失值'
        elif ED01 == 0:
            return 0
        else:
            for i in ED01:
                # 基本信息段 ED01A[1,1]
                ED01A = getTable(i, 'ED01A', 1, 1)
                # 还款表现信息段 ED01A[1,1]
                ED01B = getTable(i, 'ED01B', 1, 1)
                # 特定交易信息段 ED01A[1,1]
                ED01C = getTable(i, 'ED01C', 1, 1)
                if ED01A == [{}]:
                    continue
                elif ED01A == 0:
                    flag = True
                else:
                    ED01A = ED01A[0]
                    # 账户活动状态
                    ED01AD01 = ED01A.get("ED01AD01")
                    # 借贷账户类型
                    ED01AD02 = ED01A.get("ED01AD02")
                    # 借贷业务种类大类
                    ED01AD05 = ED01A.get("ED01AD05")
                    if num == 4:
                        if ED01AD01 not in null_type_list and ED01AD02 not in null_type_list and ED01AD05 not in null_type_list:
                            flag = True
                            if ED01AD01 == "1" and ED01AD02 in typeList and ED01AD05 in typeList2:
                                factor.append(1)
                    elif num == 5:
                        if ED01AD01 not in null_type_list and ED01AD02 not in null_type_list:
                            flag = True
                            if ED01AD01 == "1" and ED01AD02 == "C1":
                                factor.append(1)
                    elif num == 6:
                        otherResult = getED01BH(ED01B)
                        if ED01AD01 not in null_type_list and ED01AD02 not in null_type_list and otherResult not in null_type_list:
                            flag = True
                            if ED01AD01 == "1" and ED01AD02 in typeList3 and otherResult:
                                factor.append(1)
                    elif num == 7:
                        result = getED01CH(ED01C)
                        if isfloat(result):
                            flag = True
                            if result != 0:
                                factor.append(factor)
                    elif num == 14:
                        if ED01AD01 not in null_type_list and ED01AD02 not in null_type_list and ED01AD05 not in null_type_list:
                            flag = True
                            if ED01AD01 == "2" and ED01AD02 in typeList and ED01AD05 in typeList2:
                                factor.append(1)
                    elif num == 15:
                        otherResult = getED01BH(ED01B)
                        if ED01AD01 not in null_type_list and ED01AD02 not in null_type_list and otherResult not in null_type_list:
                            flag = True
                            if ED01AD01 == "2" and ED01AD02 in typeList and otherResult:
                                factor.append(1)

    return len(factor) if flag else u'缺失值'


def getED01BH(data):
    typeListA = ["21", "43", "51", "31", "32", "41", "42", "52", "61", "62", "63"]
    flag = False
    # 还款信息表现 ED01BH[0,*]
    ED01BH = getTable(data[0], 'ED01BH', 1,1)
    if ED01BH == [{}]:
        return None
    elif ED01BH == 0:
        return False
    else:
        for i in ED01BH:
            # 最近一次还款形式
            ED01BD02 = i.get("ED01BD02")
            if ED01BD02 not in null_type_list:
                flag = True
                if ED01BD02 in typeListA:
                    return True

    return False if flag else None


def getED01CH(data):
    factor = []
    flag = False
    # 特定交易信息 ED01CH[0,*]
    ED01CH = getTable(data[0], 'ED01CH', 1,1)
    if ED01CH == [{}]:
        return u'缺失值'
    elif ED01CH == 0:
        return 0
    else:
        for i in ED01CH:
            # 交易类型
            ED01CD01 = i.get("ED01CD01")
            month = i.get('ED01CR01')
            try:
                #month =month[:7]
                month = int(Formate(month))
            except:
                month =0
            if ED01CD01 not in null_type_list:
                flag = True
                #if ED01CD01 == "11" and  month not in ['2020-02','2020-03','2020-04','2020-05','2020-06','2020-07','2020-08','2020-09','2020-10','2020-11','2020-12','2021-01','2021-02','2021-03','2021-04','2021-05','2021-06','2021-07','2021-08','2021-09','2021-10','2021-11','2021-12']:
                if ED01CD01 == "11" and (month < 20200125 or month > 20211231):
                    factor.append(1)
                else:
                    factor.append(0)

    return sum(factor) if flag else u'缺失值'


def fac8(data, num):
    factor = []
    flag = False
    # 担保账户信息 EDB[1,1]
    EDB = getTable(data, 'EDB', 1, 0)
    if EDB == [{}]:
        return u'缺失值'
    elif EDB == 0:
        return 0
    else:
        # 担保账户信息明细单元 ED04[0,*]
        ED04 = getTable(EDB[0], 'ED04', 0, 1)
        if ED04 == [{}]:
            return u'缺失值'
        elif ED04 == 0:
            return 0
        else:
            for i in ED04:
                # 在保责任信息段 ED04B[1,1]
                ED04B = getTable(i, 'ED04B', 1, 1)
                if ED04B == [{}]:
                    continue
                elif ED04B == 0:
                    continue
                else:
                    ED04B = ED04B[0]
                    # 账户活动状态
                    ED04BD01 = ED04B.get("ED04BD01")
                    # 代偿（垫款）标志
                    ED04BD03 = ED04B.get("ED04BD03")
                    if ED04BD01 not in null_type_list and ED04BD03 not in null_type_list:
                        flag = True
                        if ED04BD01 == "1" and ED04BD03 == "1" and num == 8:
                            factor.append(1)
                        if ED04BD01 == "2" and ED04BD03 == "1" and num == 13:
                            factor.append(1)

    return len(factor) if flag else u'缺失值'


def fac9(data, num):
    factor = []
    flag = False
    typeList = ["61", "05", "71", "72"]
    # 担保账户信息 EDB[1,1]
    EDB = getTable(data, 'EDB', 1, 0)
    if EDB == [{}]:
        return u'缺失值'
    elif EDB == 0:
        return 0
    else:
        # 担保账户分机构汇总信息单元 ED05[0,*]
        ED05 = getTable(EDB[0], 'ED05', 0, 1)
        if ED05 == [{}]:
            return u'缺失值'
        elif ED05 == 0:
            return 0
        else:
            for i in ED05:
                # 担保交易业务种类细分
                ED050D02 = i.get("ED050D02")
                # 垫款标志
                ED050D04 = i.get("ED050D04")
                # 余额
                ED050J01 = i.get("ED050J01")
                if ED050D02 not in null_type_list and ED050D04 not in null_type_list and isfloat(ED050J01):
                    flag = True
                    if ED050D02 in typeList and ED050D04 == "1" and float(ED050J01) > 0 and num == 9:
                        factor.append(1)
                    if ED050D02 in typeList and ED050D04 == "1" and float(ED050J01) == 0 and num == 16:
                        factor.append(1)

    return len(factor) if flag else u'缺失值'


def fac10(data):
    factor = []
    flag = False
    # 相关还款责任汇总信息 EBE[1,1]
    EBE = getTable(data, 'EBE', 1, 0)
    if EBE == [{}]:
        return u'缺失值'
    elif EBE == 0:
        return 0
    else:
        # 相关还款责任汇总信息单元 EB05[0,1]
        EB05 = getTable(EBE[0], 'EB05', 0, 0)
        if EB05 == [{}]:
            return u'缺失值'
        elif EB05 == 0:
            return 0
        else:
            # 借贷信息相关还款责任汇总信息段 EB05A[0,1]
            EB05A = getTable(EB05[0], 'EB05A', 0, 1)
            if EB05A == [{}]:
                return u'缺失值'
            elif EB05A == 0:
                return 0
            else:
                # 借贷信息相关还款责任汇总信息信息 EB05AH[0,4]
                EB05AH = getTable(EB05A[0], 'EB05AH', 0, 1)
                if EB05AH == [{}]:
                    return u'缺失值'
                elif EB05AH == 0:
                    return 0
                else:
                    for i in EB05AH:
                        # 责任类型
                        EB05AD01 = i.get("EB05AD01")
                        # 被追偿账户的还款责任金额
                        EB05AJ01 = i.get("EB05AJ01")
                        # 被追偿账户数
                        EB05AS02 = i.get("EB05AS02")
                        # 被追偿账户余额
                        EB05AJ02 = i.get("EB05AJ02")
                        if EB05AD01 not in null_type_list and isfloat(EB05AJ01) \
                                and isfloat(EB05AS02) and isfloat(EB05AJ02):
                            flag = True
                            if (EB05AD01 == "1" or EB05AD01 == "9") and \
                                    (float(EB05AJ01) > 0 or float(EB05AS02) > 0 or float(EB05AJ02) > 0):
                                factor.append(1)

    return len(factor) if flag else u'缺失值'


def fac11(data, num):
    # 借贷交易汇总信息 EBB[1,1]
    EBB = getTable(data, 'EBB', 1, 0)
    if EBB == [{}]:
        return u'缺失值'
    elif EBB == 0:
        return 0
    else:
        # 信贷交易汇总信息单元 EB02[0,1]
        EB02 = getTable(EBB[0], 'EB02', 0, 1)
        if EB02 == [{}]:
            return u'缺失值'
        elif EB02 == 0:
            return 0
        else:
            # 已结清信贷交易汇总信息段 EB02B[1,1]
            EB02B = getTable(EB02[0], 'EB02B', 1, 1)
            if EB02B == [{}]:
                return u'缺失值'
            elif EB02B == 0:
                return 0
            else:
                EB02B = EB02B[0]
                if num == 11:
                    # 资产处置业务账户数
                    EB02BS01 = EB02B.get("EB02BS01")
                    # 资产处置业务余额
                    EB02BJ01 = EB02B.get("EB02BJ01")
                    if isfloat(EB02BS01) and isfloat(EB02BJ01):
                        if float(EB02BS01) > 0 or float(EB02BJ01) > 0:
                            return 1
                        else:
                            return 0
                    else:
                        return u'缺失值'
                elif num == 12:
                    # 资产处置业务账户数
                    EB02BS02 = EB02B.get("EB02BS02")
                    # 资产处置业务余额
                    EB02BJ02 = EB02B.get("EB02BJ02")
                    if isfloat(EB02BS02) and isfloat(EB02BJ02):
                        if float(EB02BS02) > 0 or float(EB02BJ02) > 0:
                            return 1
                        else:
                            return 0
                    else:
                        return u'缺失值'
                else:
                    return u'缺失值'


def R15_EC_AssetDisposalDebtGuarantorCompensation_WHB_2D():
    data = EC_DSJ_2D.get('data')
    factorList1 = []
    factorList2 = []
    factor1 = fac1(data)
    factorList1.append(factor1)
    factor2 = fac2(data, 2)
    factorList1.append(factor2)
    factor3 = fac2(data, 3)
    factorList1.append(factor3)
    factor4 = fac4(data, 4)
    factorList1.append(factor4)
    factor5 = fac4(data, 5)
    factorList1.append(factor5)
    factor6 = fac4(data, 6)
    factorList1.append(factor6)
    factor7 = fac4(data, 7)
    factorList1.append(factor7)
    factor8 = fac8(data, 8)
    factorList1.append(factor8)
    factor9 = fac9(data, 9)
    factorList1.append(factor9)
    factor10 = fac10(data)
    factorList1.append(factor10)

    factor11 = fac11(data, 11)
    factorList2.append(factor11)
    factor12 = fac11(data, 12)
    factorList2.append(factor12)
    factor13 = fac8(data, 13)
    factorList2.append(factor13)
    factor14 = fac4(data, 14)
    factorList2.append(factor14)
    factor15 = fac4(data, 15)
    factorList2.append(factor15)
    factor16 = fac9(data, 16)
    factorList2.append(factor16)

    factorSum1 = [x for x in factorList1 if x not in null_type_list and x != u'缺失值']
    factorSum2 = [x for x in factorList2 if x not in null_type_list and x != u'缺失值']

    total1 = sum(factorSum1) if len(factorSum1) > 0 else u'缺失值'
    total2 = max(factorSum2) if len(factorSum2) > 0 else u'缺失值'
    if total1 != u'缺失值' and total2 != u'缺失值':
        return total1 + total2
    elif total1 != u'缺失值':
        return total1
    elif total2 != u'缺失值':
        return total2
    else:
        return u'缺失值'


# if __name__ == '__main__':
# import json
# with open(r'C:\Users\john\Desktop\samples\data(1).json') as ff:
#     dd = json.loads(ff.read())
# EC_DSJ_2D = dd['EC_DSJ_2D']
# result = R15_EC_AssetDisposalDebtGuarantorCompensation_WHB_2D()
# print(result)
result = R15_EC_AssetDisposalDebtGuarantorCompensation_WHB_2D()
